package com.bs.resa.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;


/**
 * @Author lin
 * @date 2019/3/8 11:49
 */
@Component
public class RedisUtils {
    //操作字符串的template，StringRedisTemplate是RedisTemplate的一个子集
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    //RedisTemplate可以进行所有的操作
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public void set(String key, String value) {
        ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
        boolean bExistent = this.stringRedisTemplate.hasKey(key);
        if (bExistent) {
            logger.info("this key is bExistent!");
            this.stringRedisTemplate.delete(key);
            ops.set(key, value);
        } else {
            ops.set(key, value);
        }
    }


    public String get(String key) {

        return this.stringRedisTemplate.opsForValue().get(key);
    }

    public void del(String key) {
        this.stringRedisTemplate.delete(key);
    }

    public void setObject(String key, Object object) {
        logger.info("存入redis:{"+key+":"+object+"}");
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key, object);
    }

    public Object getObject(String key) {
        logger.info("从redis获取信息:{"+key+"}");
        return redisTemplate.opsForValue().get(key);
    }

    public void delObject(String key){
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
    }

}